package com.vf.s.mvc.biz.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.vf.core.render.HttpClientResult;
import com.vf.core.util.HttpUtil;
import com.vf.s.common.model.biz.BizLayer;
import com.vf.s.common.model.biz.Point;
import com.vf.s.common.model.biz.BizVideo;
import com.vf.s.common.model.biz.JsonMedia;
import com.vf.s.common.model.biz.JsonMediaDev;
import com.vf.s.common.model.biz.JsonMediaGroup;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;

public class BizVideoService {
	
	public void saveOrUpdateBizLayer(JSONObject cObj,String sceneId,String parentId) {
		BizLayer bizLayer = BizLayer.dao.findFirst("select * from "+BizLayer.TABLE_NAME+" where id=? and sceneId=? ",cObj.getString("id"),sceneId);
		if(bizLayer==null) {
			bizLayer = new BizLayer();
			bizLayer.setId(cObj.getString("id"));
			bizLayer.setSceneId(sceneId);
			bizLayer.save();
		}
		bizLayer.setParentId(parentId);
		bizLayer.setName(cObj.getString("name"));
		bizLayer.setType("folder");
		bizLayer.update();
	}
	
	public void saveOrUpdateBizPoint(JSONObject cObj,String sceneId) {
		Point bizPoint = Point.dao.findFirst("select * from "+Point.TABLE_NAME+" where id=? and sceneId=? ",cObj.getString("id"),sceneId);
		if(bizPoint == null) {
			bizPoint = new Point();
			bizPoint.setId(cObj.getString("id"));
			bizPoint.save();
		}
		bizPoint.setLayerId(cObj.getString("id"));
		bizPoint.setName(cObj.getString("name"));
		//bizPoint.setX("");
		//bizPoint.setY("");
		//bizPoint.setZ("");
		bizPoint.update();
	}
	
	public void saveOrUpdateBizVideo(JSONObject cObj) {
		BizVideo bizVideo = BizVideo.dao.findFirst("select * from "+BizVideo.TABLE_NAME+" where id=?",cObj.getString("id"));
		if (bizVideo == null) {
			bizVideo = new BizVideo();
			bizVideo.setId(cObj.getString("id"));
			bizVideo.save();
		}
		//bizVideo.setObjId(cObj.getString("id"));
		bizVideo.setName(cObj.getString("name"));
		bizVideo.setType("WEBRTC");
		bizVideo.setDeviceStatus(StrKit.equals("ON", cObj.getString("status"))?"1":"0");
		bizVideo.setCreateUserId(ShiroKit.getLoginUser().getId());
		bizVideo.setCreateUserName(ShiroKit.getLoginUser().getName());
		bizVideo.setSynStatus("1");
		bizVideo.setClassifyId(cObj.getString("group"));
		bizVideo.update();
	}
	
	//从RTC服务器同步数据到本地
	@Before(Tx.class)
	public String synVideoFromRTC() {
		 
		String sceneId = "";
		String rtcSerUrl=PropKit.use("app-config-dev.txt").get("rtcSerUrl");
		
		HttpClientResult result;
		List<JsonMediaGroup> listGroup=null;
		List<JsonMedia> listMedia=null ;
		List<JsonMediaDev> listMediaDev=null ;
		
		try {
			result = HttpUtil.doGet(rtcSerUrl + "/api/getMediaGroupList", null, null);
			if (result.getCode() == 200) {
				if (!StrKit.isBlank(result.getContent())) {
					 listGroup =  JSON.parseArray(result.getContent(),JsonMediaGroup.class); 
				}
			}
			
			result = HttpUtil.doGet(rtcSerUrl + "/api/getMediaList", null, null);
			if (result.getCode() == 200) {
				if (!StrKit.isBlank(result.getContent())) {
					  listMedia =  JSON.parseArray(result.getContent(),JsonMedia.class); 
				}
			}
			
			result = HttpUtil.doGet(rtcSerUrl + "/api/getMediadevList", null, null);
			if (result.getCode() == 200) {
				if (!StrKit.isBlank(result.getContent())) {
					 listMediaDev=  JSON.parseArray(result.getContent(),JsonMediaDev.class); 
				}
			}
			if(listGroup==null ||listMedia==null || listMediaDev==null ) {
				return "同步失败，数据获取为空";
			}
			
			for(JsonMedia media: listMedia) {
				boolean ifExists=true;
				BizVideo bizMedia = BizVideo.dao.findById(media.getId());
				if(bizMedia==null) {
					ifExists=false;
					bizMedia=new BizVideo();
				}
				
				bizMedia.setId(media.getId());
				bizMedia.setName(media.getName());
				bizMedia.setSceneId(sceneId);
				bizMedia.setCode("camera-point");
				bizMedia.setType("WEBRTC");
				
				for(JsonMediaDev item: listMediaDev) {
			        if(media.getDev().equals(item.getId())){
			        	bizMedia.setIp(item.getIp());
			        	bizMedia.setUsername(item.getUsr());
			        	bizMedia.setPassword(item.getPwd());
			        	bizMedia.setPort(item.getPort());
			        	bizMedia.setProtocol(item.getProtocol());
			        	bizMedia.setDeviceType(item.getType());
			        	bizMedia.setCreateTime(new Date());
			        	SimpleUser simpleUser=ShiroKit.getLoginUser();
			        	if(simpleUser!=null) {
			        		bizMedia.setCreateUserId(simpleUser.getId());
			        		bizMedia.setCreateUserName(simpleUser.getUsername());
			        	}
			        	break;
			        }
				}
				for(JsonMediaGroup item: listGroup) {
			        if(media.getGroup().equals(item.getId())){
			        	bizMedia.setGroupName(item.getName());
			        	break;
			        }
				}
				bizMedia.setSynStatus("1");
				if(!ifExists)
				{
					bizMedia.save();
				}
				else
				{
					bizMedia.update();
				}
				 
			}
			 
			return "";
			
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return "同步数据失败,"+e.getMessage();
		}
		
	}
	@Before(Tx.class)
	public String synVideoToRTC() {
		 
		String rtcSerUrl = PropKit.use("app-config-dev.txt").get("rtcSerUrl");
		HttpClientResult result;
		List<JsonMediaGroup> listGroup = null;

		try {
			result = HttpUtil.doGet(rtcSerUrl + "/api/getMediaGroupList", null, null);
			if (result.getCode() == 200) {
				if (!StrKit.isBlank(result.getContent())) {
					listGroup = JSON.parseArray(result.getContent(), JsonMediaGroup.class);
				}
			}
			if(listGroup==null) {
				return "同步失败，查询视频分组为空";
			}
			
			List<BizVideo> lists = BizVideo.dao.find("select * from " + BizVideo.TABLE_NAME + " where type='WEBRTC' and groupName is not null AND  synStatus='0' ");
			for (BizVideo bizVideo : lists) {
				boolean ifExistsGroup = false;
				//无分组信息不同步
				if(bizVideo.getGroupName()==null || bizVideo.getGroupName().length()==0) {
					break;
				}
				String groupId="";
				for (JsonMediaGroup item : listGroup) {
					if ( item.getName().equals(bizVideo.getGroupName())) {
						ifExistsGroup = true;
						groupId=item.getId();
						break;
					}
				}
				if (!ifExistsGroup) {
					JsonMediaGroup jsonMediaGroup = new JsonMediaGroup();
					jsonMediaGroup.setId(UUID.randomUUID().toString());
					jsonMediaGroup.setName(bizVideo.getGroupName());
					jsonMediaGroup.setParentId("root");
					String param = "id=" + jsonMediaGroup.getId() + "&name=" + jsonMediaGroup.getName() + "&parentid="
							+ jsonMediaGroup.getParentId();
					result = HttpUtil.doGet(rtcSerUrl + "/api/addGroup?" + param, null, null);
					if (result.getCode() != 200) {
						return "同步失败，同步视频分组时失败";
					} else {
						listGroup.add(jsonMediaGroup);
					}
					groupId= jsonMediaGroup.getId();
				}
				Map dev = new HashMap();
				dev.put("group", groupId);
				dev.put("id", bizVideo.getId());
				dev.put("name", bizVideo.getName());
				dev.put("type", bizVideo.getDeviceType());
				dev.put("protocol", bizVideo.getProtocol());
				dev.put("ip", bizVideo.getIp());
				dev.put("port", bizVideo.getPort());
				dev.put("usr", bizVideo.getUsername());
				dev.put("pwd", bizVideo.getPassword());

				Map channel = new HashMap();
				channel.put("group", groupId);
				channel.put("id", bizVideo.getId());
				channel.put("name", bizVideo.getName());
				//channel.put("video", null);
				//channel.put("options", null);
				channel.put("channelNum", bizVideo.getChannelNum());

				Map postData = new HashMap();
				postData.put("dev", dev);
				postData.put("channel", channel);

			     String jsonParam= JSON.toJSONString(postData);
//				result =HttpUtil.doPost(rtcSerUrl + "/api/addMedia",null,jsonParam);
//				if (result.getCode() != 200) {
//					System.out.println("同步"+bizVideo.getId()+"失败");
//				} else {
//					bizVideo.setSynStatus("1");
//					bizVideo.update();
//				}
			}
			return "";

		} catch (Exception e) {

			e.printStackTrace();
			return "同步视频失败," + e.getMessage();
		}
	}
	
}
